import time

# from Mitama.many.py.Loop import loop
# from util.HwndList import get

import os
import random
import win32gui

# from util import WindowCapture
# from util.MatchImg import matchImg
# from util.Cursor import click_it

import win32api
import win32gui
import win32ui

import win32con

import aircv as ac

import win32api
import win32gui
from ctypes import windll
import time

import win32con


def clickLeftCur():
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN | win32con.MOUSEEVENTF_LEFTUP, 0, 0)

def leftDown(pos, hd):
    handle = hd
    client_pos = win32gui.ScreenToClient(handle, pos)
    tmp = win32api.MAKELONG(client_pos[0], client_pos[1])
    win32gui.SendMessage(handle, win32con.WM_ACTIVATE, win32con.WA_ACTIVE, 0)
    win32gui.SendMessage(handle, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, tmp)

def leftUp(pos, hd):
    handle = hd
    client_pos = win32gui.ScreenToClient(handle, pos)
    tmp = win32api.MAKELONG(client_pos[0], client_pos[1])
    win32gui.SendMessage(handle, win32con.WM_ACTIVATE, win32con.WA_ACTIVE, 0)
    win32gui.SendMessage(handle, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, tmp)

def click_it(pos, hd):
    handle = hd
    # moveCurPos(pos[0], pos[1])
    client_pos = win32gui.ScreenToClient(handle, pos)
    tmp = win32api.MAKELONG(client_pos[0], client_pos[1])
    win32gui.SendMessage(handle, win32con.WM_ACTIVATE, win32con.WA_ACTIVE, 0)
    win32gui.SendMessage(handle, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, tmp)
    win32gui.SendMessage(handle, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, tmp)

def click_it_a(pos, hd):
    handle = hd
    client_pos = win32gui.ScreenToClient(handle, pos)
    tmp = win32api.MAKELONG(client_pos[0], client_pos[1])
    win32gui.PostMessage(handle, win32con.WM_ACTIVATE, win32con.WA_ACTIVE, 0)
    win32gui.PostMessage(handle, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, tmp)
    win32gui.PostMessage(handle, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, tmp)

def moveCurPos(x, y):  # 移动鼠标
    windll.user32.SetCursorPos(x, y)


def getCurPos():  # 获得鼠标位置信息，这个再实际代码没用上，调试用得上
    return win32gui.GetCursorPos()

def dragCur(param, hd):
    leftDown((param[0], param[1]), hd)
    leftUp((param[0], param[1]), hd)



def matchImg(imgsrc, imgobj, confidence):  # imgsrc=原始图像，imgobj=待查找的图片
    """

    :rtype: object
    """
    imsrc = ac.imread(imgsrc)
    imobj = ac.imread(imgobj)
    match_result = ac.find_template(imsrc, imobj, confidence)
    # {'confidence': 0.5435812473297119, 'rectangle': ((394, 384), (394, 416), (450, 384), (450, 416)), 'result': (422.0, 400.0)}
    if match_result is not None:
        match_result['shape'] = (imsrc.shape[1], imsrc.shape[0])  # 0为高，1为宽

    return match_result


def window_capture(filename, hd):
    hwnd = hd  # 窗口的编号，0号表示当前活跃窗口
    # 根据窗口句柄获取窗口的设备上下文DC（Divice Context）
    hwndDC = win32gui.GetWindowDC(hwnd)
    # 根据窗口的DC获取mfcDC
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    # mfcDC创建可兼容的DC
    saveDC = mfcDC.CreateCompatibleDC()
    # 创建bigmap准备保存图片
    saveBitMap = win32ui.CreateBitmap()
    # 获取监控器信息
    MoniterDev = win32api.EnumDisplayMonitors(None, None)
    w = MoniterDev[0][2][2]
    h = MoniterDev[0][2][3]
    #print(w, h)#图片大小
    # 为bitmap开辟空间
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
    # 高度saveDC，将截图保存到saveBitmap中
    saveDC.SelectObject(saveBitMap)
    # 截取从左上角（0，0）长宽为（w，h）的图片
    saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY)
    saveBitMap.SaveBitmapFile(saveDC, filename)
    win32gui.DeleteObject(saveBitMap.GetHandle())
    saveDC.DeleteDC()


hwnd_title = dict()

def get_all_hwnd(hwnd, mouse):
    if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
        hwnd_title.update({hwnd: win32gui.GetWindowText(hwnd)})

def get():
    list = [];
    win32gui.EnumWindows(get_all_hwnd, 0)
    for h, t in hwnd_title.items():
        if t != "":
            # if t == '夜神模拟器':
            if t == '阴阳师-网易游戏':
                list.append(h)
                print(h)
    return list;


def loop(hwnd):
    baseImg = "../images/blackground.jpg"  # 储存的文件名  # 储存的文件名
    rect = win32gui.GetWindowRect(hwnd)
    window_capture(baseImg, hwnd)  # 对整个屏幕截图，并保存截图为baseImg
    # 遍历所有图片
    for filename in os.listdir(r"../images/images-fight"):  # listdir的参数是文件夹的路径
        imagePath = "../images/images-fight/" + filename
        print(imagePath)
        res = matchImg(baseImg, imagePath, 0.8)
        if res is None:
            continue
        if filename == "reward.png":
            x = rect[0] + 20
            y = rect[1] + 560
        else:
            x = rect[0] + res["result"][0]
            y = rect[1] + res["result"][1]


        move_x = random.randint(int(x) - 2, int(x) + 2)
        move_y = random.randint(int(y) - 2, int(y) + 2)
        print(move_x, move_y)
        click_it((move_x, move_y), hwnd)
        if filename.__contains__("zhandou"):
            time.sleep(25)



def main():
    print("欢迎来到阴阳师联盟！")
    arg = 0
    tt = 3
    # if sys.argv.__len__() > 1:  #多人组队
    #     arg = sys.argv[1]
    # else:
    #     tt = 1
    #获取所有阴阳师句柄
    list = get()

    # list = [395746, 263310]
    while True:
        time.sleep(tt)  # 设置隔2秒运行一次

        #循环所有句柄
        for hd in list:
            loop(hd)

if __name__=="__main__":
    main()





